package 反射;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @功能
 * @创建时间 2020/5/6
 */

public class MyTest {
    @Test
    public void test() throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        //创建对象
        UserService userService = new UserService();
        System.out.println(userService);
        //获取所有的属性
        Field field = clazz.getDeclaredField("userService");
        field.setAccessible(true);
        //只有通过方法才能获取具体的属性值
        String name = field.getName();
        System.err.println(name);
      //  UserService userService1 = (UserService)field.get(null);
        //拼接方法名
        name = name.substring(0,1).toUpperCase()+name.substring(1,name.length());
        String setName = "set" + name;
        Method method = clazz.getMethod(setName,userService.getClass());
        try {
            Class clazz1 = Class.forName("反射.UserService");
            Method method1 = clazz1.getDeclaredMethod("print",new Class[]{String.class,Integer.class});
            try {
                method1.invoke((UserService)clazz1.newInstance(),"eq",1);
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //反射
        method.invoke(userController,userService);
 //       System.err.println(userController.getUserService());
    }
}